import Cesium from '../../Ces/Cesium';
import CesiumNavigation from './CesiumNavigation.js';
import './Styles/cesium-navigation.css';

interface Viewer {
    cesiumWidget: CesiumWidget;
    extend(mixin: (viewer: Viewer, options: any) => void): void;
}

interface CesiumWidget {
    cesiumNavigation?: CesiumNavigation;
}

function viewerCesiumNavigationMixin(viewer: Viewer, options: any): void {
    if (!Cesium.defined(viewer)) {
        throw new Cesium.DeveloperError('viewer is required.');
    }

    const cesiumNavigation = init(viewer, options);

    cesiumNavigation.addOnDestroyListener((function (viewer: any) {
        return function () {
            delete viewer.cesiumNavigation;
        };
    })(viewer));

    Object.defineProperties(viewer, {
        cesiumNavigation: {
            configurable: true,
            get: function () {
                return viewer.cesiumWidget.cesiumNavigation;
            }
        }
    });
}

/**
 *
 * @param {CesiumWidget} cesiumWidget The cesium widget instance.
 * @param {{}} options The options.
 */
viewerCesiumNavigationMixin.mixinWidget = function (cesiumWidget: CesiumWidget, options: any): CesiumNavigation {
    return init.apply(undefined, [cesiumWidget, options]);
};

/**
 * @param {Viewer|CesiumWidget} viewerCesiumWidget The Viewer or CesiumWidget instance
 * @param {{}} options the options
 */
function init(viewerCesiumWidget: Viewer | CesiumWidget, options: any): CesiumNavigation {
    //@ts-ignore
    const cesiumNavigation = new CesiumNavigation(viewerCesiumWidget);

    const cesiumWidget = Cesium.defined((viewerCesiumWidget as Viewer).cesiumWidget)? (viewerCesiumWidget as Viewer).cesiumWidget : viewerCesiumWidget as CesiumWidget;

    Object.defineProperties(cesiumWidget, {
        cesiumNavigation: {
            configurable: true,
            get: function () {
                return cesiumNavigation;
            }
        }
    });

    cesiumNavigation.addOnDestroyListener((function (cesiumWidget: CesiumWidget) {
        return function () {
            delete cesiumWidget.cesiumNavigation;
        };
    })(cesiumWidget));

    return cesiumNavigation;
}

export default viewerCesiumNavigationMixin;
